package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.common.utils.DateTimeTransToDayOfWeek;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.hosp.ScheduleQueryVo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Resource
    private ScheduleRepository scheduleRepository;
    @Resource
    private MongoTemplate mongoTemplate;
    @Resource
    private HospitalService hospitalService;
    @Resource
    private DepartmentService departmentService;

    @Override
    public void saveSchedule(Map<String, Object> paramMap) {
        // 参数解析
        String jsonString = JSONObject.toJSONString(paramMap);
        Schedule schedule = JSONObject.parseObject(jsonString, Schedule.class);
        // 查询排班信息判断是否存在
        Schedule targetSchedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(
                schedule.getHoscode(), schedule.getHosScheduleId());
        // 如果不存在, 进行添加
        if (!ObjectUtils.isEmpty(targetSchedule)) {
            BeanUtils.copyProperties(targetSchedule, schedule);
            scheduleRepository.save(schedule);
            System.out.println("如果不存在, 进行添加... ");
        } else {
            // 如果存在, 进行修改
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
            System.out.println("如果存在, 进行修改... ");
        }
    }

    @Override
    public Page<Schedule> findSchedulePage(int pageNum, int pageSize, ScheduleQueryVo scheduleQueryVo) {
        // 分页处理
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        PageRequest pageable = PageRequest.of(pageNum = 1, pageSize, sort);

        // 创建实体对象进行参数介绍
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        schedule.setIsDeleted(0);

        // 创建匹配器,也就是如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);

        // 创建实例查询
        Example<Schedule> example = Example.of(schedule, matcher);
        // 调用查询方法
        Page<Schedule> schedulePage = scheduleRepository.findAll(example, pageable);
        List<Schedule> schedulePageContent = schedulePage.getContent();
        // System.out.println("schedulePageContent = " + schedulePageContent);
        return schedulePage;
    }

    @Override
    public void removeSchedule(String hoscode, String hosScheduleId) {
        // 查询排班信息
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        schedule.setCreateTime(new Date());
        schedule.setIsDeleted(1);
        if (ObjectUtils.isEmpty(schedule)) {
            throw new YyghException(ResultCodeEnum.SERVICE_ERROR);
        } else {
            scheduleRepository.save(schedule);
        }


    }

    /**
     * 排班日期分页列表
     * --->>>根据医院编号 和 科室编号 ，查询排班规则数据
     * Map<String, Object> getRuleSchedule(long page, long limit, String hoscode, String depcode);
     *
     * @param page
     * @param limit
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Map<String, Object> getRuleScheduleByHoscodeAndDepcode(long page, long limit, String hoscode, String depcode) {
        // 0, 创建map集合用于封装结果
        Map<String, Object> resultMap = new HashMap<>();
        // 封装查询条件
        // 1, 根据医院hoscode和depcode进行查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        Aggregation agg = Aggregation.newAggregation(
                // 2, 根据工作日期workDate进行分组
                Aggregation.match(criteria), // 匹配条件
                Aggregation.group("workDate").first("workDate").as("workDate") // 分组字段
                        // 3, 统计号源数据
                        .count().as("docCount")  // 就诊医生人数
                        .sum("reservedNumber").as("reservedNumber")  // 科室可预约数
                        .sum("availableNumber").as("availableNumber"), // 科室剩余预约数
                // 排序
                Aggregation.sort(Sort.Direction.DESC, "workDate"),
                // 4, 实现分页查询
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)
        );
        // 调用聚合查询方法实现分页查询
        AggregationResults<BookingScheduleRuleVo> aggregationResults =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggregationResults.getMappedResults();
        // 分析分组查询的总记录数 totalCount
        int totalCount = 0;
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate"
                ));
        AggregationResults<BookingScheduleRuleVo> totalAggResults =
                mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        totalCount = totalAggResults.getMappedResults().size();

        // 日期格式转换处理,把日期获取对应的星期
        bookingScheduleRuleVoList.forEach(bookingScheduleRuleVo -> {

            Date workDate = bookingScheduleRuleVo.getWorkDate();
            // 调用工具类进行转换日期格式
            String dayOfWeek = DateTimeTransToDayOfWeek.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

        });
        // 封装数据,可预约排班规则数据 || 总记录数totalCount || 造baseMap封装其他数据: 医院的名称hosName
        resultMap.put("bookingScheduleRuleList", bookingScheduleRuleVoList);
        resultMap.put("total", totalCount);

        // 造baseMap封装其他数据
        Map<String, Object> baseMap = new HashMap<>();
        String hospitalName = hospitalService.getHospitalNameByHoscode(hoscode);
        baseMap.put("hosName", hospitalName);
        resultMap.put("baseMap", baseMap);
        // 返回map数据
        return resultMap;
    }

    /**
     * =======根据医院编号 、科室编号和工作日期，查询排班详细信息
     *
     * @param hoscode
     * @param depcode
     * @param workDate
     * @return
     */
    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        // 根据闯进来的参数到mogo查询
        List<Schedule> scheduleListResult = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate
                (
                        hoscode,  // 医院编号
                        depcode,  // 科室编号
                        new DateTime(workDate).toDate()  // 工作日期
                );
        // 结果集进行进行流转换封装方法调用
        scheduleListResult.stream().forEach(schedule -> this.packageSchedule(schedule));
        // 返回结果集
        return scheduleListResult;
    }

    /**
     * 获取可预约的排班数据
     *
     * @param page
     * @param limit
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Map<String, Object> getBookingScheduleRule(Long page, Long limit, String hoscode, String depcode) {
        // 创建map集合,便于封装数据
        Map<String, Object> resultMap = new HashMap<>();
        // 获取预约规则
        // 根据医院编号获取预约规则
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        // 判断医院是空就跑数据异常
        if (ObjectUtils.isEmpty(hospital)) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }

        // 获取可预约的日期数据(:分页  this.getListData(page,limit,bookingRule)
        BookingRule bookingRule = hospital.getBookingRule();
        IPage<Date> iPage = this.getListData(page, limit, bookingRule);
        // 获取当前可以预约的日期
        List<Date> dateList = iPage.getRecords();
        // 查询获取可预约日期科室剩余预约数量
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(dateList);
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria), // 匹配条件
                Aggregation.group("workDate").first("workDate").as("workDate") // 分组字段
                        // 3, 统计号源数据
                        .count().as("docCount")  // 就诊医生人数
                        .sum("availableNumber").as("availableNumber")  // 科室可预约数
                        .sum("reservedNumber").as("reservedNumber") // 科室剩余预约数
        );

        // 调用mogoTemplate方法进行查询
        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);

        // 获取科室剩余预约数量
        List<BookingScheduleRuleVo> scheduleRuleVoList = aggregationResults.getMappedResults();

        // 合并数据,将统计数据SchedulVo根据"安排日期"合并BookingRuleVo
        Map<Date, BookingScheduleRuleVo> scheduleRuleVoMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(scheduleRuleVoList)) {
            scheduleRuleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }

        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for (int i = 0, len = dateList.size(); i < len; i++) {
            Date date = dateList.get(i);

            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleRuleVoMap.get(date);
            if (null == bookingScheduleRuleVo) { // 说明当天没有排班医生
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前预约日期为周几
            String dayOfWeek = DateTimeTransToDayOfWeek.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if (i == len - 1 && page == iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间， 不能预约
            if (i == 0 && page == 1) {
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if (stopTime.isBeforeNow()) {
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        //可预约日期规则数据
        resultMap.put("bookingScheduleList", bookingScheduleRuleVoList);
        resultMap.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospitalNameByHoscode(hoscode));
        //科室
        Department department = departmentService.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        // 封装其他数据
        resultMap.put("baseMap", baseMap);

        // 返回map集合
        return resultMap;
    }

    @Override
    public Schedule getById(String scheduleId) {
        Schedule schedule = scheduleRepository.findById(scheduleId).get();

        Schedule packageSchedule = this.packageSchedule(schedule);

        return packageSchedule;
    }

    /**
     * todo:5.封装Feign调用获取排班下单信息接口
     *
     * @param scheduleId
     * @return
     */
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        // 下单数据封装
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        // 获取排班信息
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        if (ObjectUtils.isEmpty(schedule)) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }

        // 获取医院预约数据
        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        if (ObjectUtils.isEmpty(hospital)) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        // 医院的预约规则
        BookingRule bookingRule = hospital.getBookingRule();
        if (ObjectUtils.isEmpty(bookingRule)) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }

        // 封装排班订单数据
        scheduleOrderVo.setHoscode(hospital.getHoscode());
        scheduleOrderVo.setHosname(hospital.getHosname());
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepNameByHoscodeAndDepcode(schedule.getHoscode(), schedule.getDepcode()));
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        // 退号截至天数,
        Integer quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        // 预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        // 当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());

        // 预约截至时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        return scheduleOrderVo;
    }

    @Override
    public void updateSchedule(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        //主键一致就是更新
        scheduleRepository.save(schedule);

    }

    private IPage<Date> getListData(Long page, Long limit, BookingRule bookingRule) {
        //当天放号时间
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        //预约周期
        int cycle = bookingRule.getCycle();
        //如果当天放号时间已过，则预约周期后一天为即将放号时间，周期加1
        if (releaseTime.isBeforeNow()) cycle += 1;
        //可预约所有日期，最后一天显示即将放号倒计时
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            //计算当前预约日期
            DateTime curDateTime = new DateTime().plusDays(i);
            String dateString = curDateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }
//日期分页，由于预约周期不一样，页面一排最多显示7天数据，多了就要分页显示
        List<Date> pageDateList = new ArrayList<>();
        long start = (page - 1) * limit;
        long end = (page - 1) * limit + limit;
        if (end > dateList.size()) end = dateList.size();
        for (long i = start; i < end; i++) {
            pageDateList.add(dateList.get((int) i));
        }

        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page, 7, dateList.size());
        iPage.setRecords(pageDateList);
        return iPage;


    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }


    /**
     * 排班详细信息结果集进行封装
     *
     * @param schedule
     */
    private Schedule packageSchedule(Schedule schedule) {
        // 设置医院名称
        String hospitalName = hospitalService.getHospitalNameByHoscode(schedule.getHoscode());
        schedule.getParam().put("hosname", hospitalName);

        // 设置科室名称
        String depName = departmentService.getDepNameByHoscodeAndDepcode(schedule.getHoscode(), schedule.getDepcode());
        schedule.getParam().put("depName", depName);

        // 设置日期对应的星期
        DateTime dateTime = new DateTime(schedule.getWorkDate());
        String dayOfWeek = DateTimeTransToDayOfWeek.getDayOfWeek(dateTime);
        schedule.getParam().put("dayOfWeek", dayOfWeek);

        return schedule;
    }


}
